/*
 * Webcam_TestView.java
 */

package webcam_test;

import java.awt.Component;
import java.awt.Image;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Vector;
import javax.media.CaptureDeviceInfo;
import javax.media.CaptureDeviceManager;
import javax.media.Control;
import javax.media.Format;
import javax.media.Manager;
import javax.media.MediaLocator;
import javax.media.Player;
import javax.media.control.FormatControl;
import org.jdesktop.application.Action;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.FrameView;
import javax.swing.JDialog;
import javax.swing.JFrame;

import javax.media.control.FrameGrabbingControl;
import javax.media.format.VideoFormat;
import javax.media.protocol.CaptureDevice;
import javax.media.protocol.DataSource;
import javax.media.util.BufferToImage;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;

/**
 * The application's main frame.
 */
public class Webcam_TestView extends FrameView {

    //private static String cameraString = "vfw:Microsoft WDM Image Capture (Win32):0";
    private static String locatorString = "vfw://0";
    private Player player;
    private MediaLocator locator;
    private Component display;
    private FrameGrabbingControl grabber;
    private volatile Image img;
    private BufferToImage btoi;

    public Webcam_TestView(SingleFrameApplication app) {
        super(app);
        initComponents();
        try {
            locator = new MediaLocator(locatorString);
            //CaptureDevice source = (CaptureDevice) Manager.createDataSource(locator);
            //FormatControl[] formatControls = source.getFormatControls();
            //System.out.println("Format control #: "+formatControls.length);
            //Format[] formats = formatControls[0].getSupportedFormats();
            //Vector<CaptureDeviceInfo> captureDevices = CaptureDeviceManager.getDeviceList(null);
            //System.out.println("Capture device #: "+captureDevices.size());
            player = Manager.createRealizedPlayer(locator);
            //player.start();
            //player.stop();
            /*Control[] controls = player.getControls();
            FormatControl formatControl = null;
            for(int x=0; x < controls.length; x++){
            if(controls[x] instanceof FormatControl){
            formatControl = (FormatControl) controls[x];
            }
            }
            if(formatControl != null){
            Format[] formats = formatControl.getSupportedFormats();
            System.out.println(formats.length);
            for(int x =0; x < formats.length; x++){
            System.out.println("format: "+formats[x].toString());
            }
            formatControl.setFormat(formats[4]);
            }*/
            player.start();
            Thread.sleep(1000);
            display = player.getVisualComponent();
            if(display != null){
                mainPanel.add(display);
            }
        } catch (Exception e){
            JOptionPane.showMessageDialog(null, "ERROR: "+e.getMessage(), "ERROR", JOptionPane.ERROR_MESSAGE);
            System.exit(0);
        }
        this.getFrame().addWindowListener(new WindowAdapter(){
            @Override
            public void windowClosing(WindowEvent e){
                player.close();
                player.deallocate();
            }
        });
        grabber = (FrameGrabbingControl) player.getControl("javax.media.control.FrameGrabbingControl");
        btoi = new BufferToImage((VideoFormat) grabber.grabFrame().getFormat());
        final Thread captureThread = new Thread(new Runnable(){
            public void run() {
                while(true){
                    captureFrame();
                }
            }
        });
        captureThread.setPriority(Thread.MAX_PRIORITY);
        SwingUtilities.invokeLater(new Runnable(){
            public void run() {
                captureThread.start();
            }
        });
    }

    private void captureFrame(){
        img = btoi.createImage(grabber.grabFrame());
        mainPanel.getGraphics().drawImage(img, 0, 0,640,480, null);
    }

    @Action
    public void showAboutBox() {
        if (aboutBox == null) {
            JFrame mainFrame = Webcam_TestApp.getApplication().getMainFrame();
            aboutBox = new Webcam_TestAboutBox(mainFrame);
            aboutBox.setLocationRelativeTo(mainFrame);
        }
        Webcam_TestApp.getApplication().show(aboutBox);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        mainPanel = new javax.swing.JPanel();

        mainPanel.setName("mainPanel"); // NOI18N

        javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
        mainPanel.setLayout(mainPanelLayout);
        mainPanelLayout.setHorizontalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        mainPanelLayout.setVerticalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );

        setComponent(mainPanel);
    }// </editor-fold>//GEN-END:initComponents

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel mainPanel;
    // End of variables declaration//GEN-END:variables

    private JDialog aboutBox;
}
